<template>
  <view class="payment-container">
    <view class="payment-header">
      <view class="order-info">
        <text class="title">订单支付</text>
        <text class="amount">¥{{ amount }}</text>
        <text class="timeout">支付倒计时：{{ remainingTime }}秒</text>
      </view>
    </view>

    <view class="payment-content">
      <view class="qr-wrapper" v-if="qrCodeImage">
        <image 
          :src="qrCodeImage" 
          mode="aspectFit" 
          class="qr-code"
          @error="handleImageError"
        ></image>
        <text class="tip">请使用微信扫码支付</text>
      </view>
      
      <view class="loading" v-else>
        <text>正在生成支付二维码...</text>
      </view>

      <view class="order-detail">
        <view class="info-item">
          <text class="label">订单编号</text>
          <text class="value">{{ orderNumber }}</text>
        </view>
        <view class="info-item">
          <text class="label">套餐名称</text>
          <text class="value">{{ orderInfo.setmealName }}</text>
        </view>
        <view class="info-item">
          <text class="label">预约人</text>
          <text class="value">{{ orderInfo.orderName }}</text>
        </view>
        <view class="info-item">
          <text class="label">预约日期</text>
          <text class="value">{{ orderInfo.orderDate }}</text>
        </view>
      </view>

      <view class="action-buttons">
        <button class="cancel-btn" @click="handleCancelPayment">取消支付</button>
      </view>
    </view>
  </view>
</template>

<script>
const BASE_URL = 'http://localhost:8188'

export default {
  data() {
    return {
      orderInfo: {},
      qrCodeImage: '',
      orderNumber: '',
      checkTimer: null,
      timeoutTimer: null,
      remainingTime: 60,
      amount: '0.00'
    }
  },

  onLoad(options) {
    console.log('支付页面参数:', options)
    if (options.orderInfo) {
      try {
        this.orderInfo = JSON.parse(decodeURIComponent(options.orderInfo))
        console.log('解析后的订单信息:', this.orderInfo)
        this.amount = this.orderInfo.amount || '0.00'
        this.createPayment()
        this.startTimeoutTimer()
      } catch (error) {
        console.error('解析订单信息失败:', error)
        uni.showToast({
          title: '订单信息错误',
          icon: 'none'
        })
      }
    }
  },

  onUnload() {
    if (this.checkTimer) {
      clearInterval(this.checkTimer)
    }
    if (this.timeoutTimer) {
      clearInterval(this.timeoutTimer)
    }
  },

  methods: {
    createPayment() {
      uni.showLoading({
        title: '正在生成支付码...'
      })

      uni.request({
        url: `${BASE_URL}/api/order/mySetmealOrderCreate`,
        method: 'POST',
        data: this.orderInfo,
        success: (res) => {
          console.log('支付创建响应:', res.data)
          if (res.data.code === 200) {
            this.qrCodeImage = res.data.data['QR code image']
            this.orderNumber = res.data.data['Order number']
            console.log('二维码图片数据:', this.qrCodeImage)
            
            this.startCheckPaymentStatus()
          } else {
            uni.showToast({
              title: res.data.errorMessage || '生成支付二维码失败',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          console.error('请求失败:', err)
          uni.showToast({
            title: '生成支付二维码失败',
            icon: 'none'
          })
        },
        complete: () => {
          uni.hideLoading()
        }
      })
    },

    startCheckPaymentStatus() {
      this.checkTimer = setInterval(() => {
        uni.request({
          url: `${BASE_URL}/api/order/checkPayStatus`,
          method: 'GET',
          data: {
            no: this.orderNumber
          },
          success: (res) => {
            console.log('支付状态检查:', res.data)
            if (res.data.code === 200 && res.data.errorMessage === 'SUCCESS') {
              clearInterval(this.checkTimer)
              clearInterval(this.timeoutTimer)
              
              uni.showToast({
                title: '支付成功',
                icon: 'success',
                duration: 2000
              })

              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                  success: () => {
                    const pages = getCurrentPages()
                    const prevPage = pages[pages.length - 2]
                    if (prevPage && prevPage.$vm && prevPage.$vm.loadOrders) {
                      prevPage.$vm.loadOrders()
                    }
                  }
                })
              }, 1500)
            }
          },
          fail: (err) => {
            console.error('检查支付状态失败:', err)
          }
        })
      }, 3000)
    },

    startTimeoutTimer() {
      this.timeoutTimer = setInterval(() => {
        this.remainingTime--
        if (this.remainingTime <= 0) {
          clearInterval(this.timeoutTimer)
          clearInterval(this.checkTimer)
          
          uni.showToast({
            title: '支付超时',
            icon: 'none',
            duration: 2000
          })

          setTimeout(() => {
            uni.navigateBack()
          }, 2000)
        }
      }, 1000)
    },

    handleImageError(e) {
      console.error('二维码图片加载失败:', e)
      uni.showToast({
        title: '二维码加载失败',
        icon: 'none'
      })
    },

    handleCancelPayment() {
      uni.showModal({
        title: '提示',
        content: '确定要取消支付吗？取消后需要重新预约',
        success: (res) => {
          if (res.confirm) {
            // 清除所有定时器
            clearInterval(this.checkTimer)
            clearInterval(this.timeoutTimer)
            
            // 返回上一页
            uni.navigateBack({
              delta: 1
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.payment-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.payment-header {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;

  .order-info {
    text-align: center;

    .title {
      font-size: 32rpx;
      color: #333;
      margin-bottom: 20rpx;
      display: block;
    }

    .amount {
      font-size: 48rpx;
      font-weight: bold;
      color: #f56c6c;
      margin-bottom: 10rpx;
      display: block;
    }

    .timeout {
      font-size: 24rpx;
      color: #666;
      display: block;
    }
  }
}

.payment-content {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;

  .qr-wrapper {
    text-align: center;
    padding: 30rpx 0;

    .qr-code {
      width: 400rpx;
      height: 400rpx;
      margin-bottom: 20rpx;
    }

    .tip {
      font-size: 28rpx;
      color: #666;
    }
  }

  .loading {
    text-align: center;
    padding: 50rpx 0;
    color: #666;
  }

  .order-detail {
    margin-top: 30rpx;
    border-top: 1rpx solid #eee;
    padding-top: 30rpx;

    .info-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;
      font-size: 28rpx;

      .label {
        color: #666;
      }

      .value {
        color: #333;
        max-width: 70%;
        word-break: break-all;
      }

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .action-buttons {
    margin-top: 40rpx;
    padding: 20rpx;

    .cancel-btn {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background: #f5f5f5;
      color: #666;
      border-radius: 40rpx;
      font-size: 28rpx;
      border: none;

      &:active {
        opacity: 0.8;
      }
    }
  }
}
</style> 